#!/usr/bin/env python3
"""
MyLangExtract 集成示例
演示如何在新项目中使用构建好的包
"""

import os
import tempfile
import subprocess
import sys

def create_new_project_example():
    """创建一个新项目示例，演示如何集成 MyLangExtract"""
    
    # 创建临时目录作为新项目
    with tempfile.TemporaryDirectory() as temp_dir:
        print(f"📁 创建新项目目录: {temp_dir}")
        
        # 获取当前 wheel 包路径
        wheel_path = os.path.join(os.path.dirname(__file__), "dist", "mylangextract-1.0.0-py3-none-any.whl")
        
        if not os.path.exists(wheel_path):
            print("❌ 请先运行 'uv build' 构建包")
            return
        
        print(f"📦 找到包文件: {wheel_path}")
        
        # 创建新项目的代码文件
        project_code = '''
import os
from mylangextract import create_extractor, Extraction, ExampleData

def main():
    # 检查 API Key
    api_key = os.environ.get('ZHIPU_API_KEY')
    if not api_key:
        print("⚠️  请设置 ZHIPU_API_KEY 环境变量")
        return
    
    print("🚀 创建提取器...")
    extractor = create_extractor(provider="zhipu", model="glm-4")
    
    # 定义示例
    examples = [
        ExampleData(
            text="张三是一位资深的软件工程师，专注于人工智能领域。",
            extractions=[
                Extraction(
                    extraction_class="person",
                    extraction_text="张三",
                    attributes={"profession": "软件工程师", "field": "人工智能"}
                )
            ]
        )
    ]
    
    # 执行提取
    text = "李四是一名数据科学家，在机器学习方面有丰富经验。"
    print(f"📝 处理文本: {text}")
    
    result = extractor.extract(
        text=text,
        prompt="提取人物信息，包括姓名和职业背景",
        examples=examples
    )
    
    print("✅ 提取结果:")
    for extraction in result.extractions:
        print(f"   - {extraction.extraction_class}: {extraction.extraction_text}")
        print(f"     属性: {extraction.attributes}")

if __name__ == "__main__":
    main()
'''
        
        # 写入项目代码
        project_file = os.path.join(temp_dir, "main.py")
        with open(project_file, 'w', encoding='utf-8') as f:
            f.write(project_code)
        
        print("📝 创建项目代码文件")
        
        # 创建 pyproject.toml
        pyproject_content = '''
[project]
name = "my-extraction-project"
version = "0.1.0"
dependencies = []

[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"
'''
        
        pyproject_file = os.path.join(temp_dir, "pyproject.toml")
        with open(pyproject_file, 'w') as f:
            f.write(pyproject_content)
        
        print("⚙️  创建 pyproject.toml")
        
        # 模拟安装过程（这里只是演示，实际中会真正安装）
        print("\n🔧 安装步骤（在实际项目中运行）:")
        print(f"   cd {temp_dir}")
        print("   uv init")
        print(f"   uv add {wheel_path}")
        print("   uv run main.py")
        
        print("\n📋 或者使用 pip:")
        print(f"   pip install {wheel_path}")
        print("   python main.py")
        
        print(f"\n📁 项目文件已创建在: {temp_dir}")
        print("📄 项目结构:")
        for root, dirs, files in os.walk(temp_dir):
            level = root.replace(temp_dir, '').count(os.sep)
            indent = ' ' * 2 * level
            print(f"{indent}{os.path.basename(root)}/")
            subindent = ' ' * 2 * (level + 1)
            for file in files:
                print(f"{subindent}{file}")
        
        # 显示项目代码内容
        print("\n📝 项目代码内容:")
        print("=" * 50)
        print(project_code)
        print("=" * 50)

if __name__ == "__main__":
    create_new_project_example()
